<template>
  <view class="container">
    <view class="register-form">
      <view class="form-header">
        <text class="form-title">创建账户</text>
        <text class="form-subtitle">加入我们的音乐世界</text>
      </view>

      <view class="form-content">
        <view class="input-group">
          <input 
            class="form-input" 
            placeholder="请输入用户名" 
            v-model="registerForm.username"
            maxlength="50"
          />
        </view>

        <view class="input-group">
          <input 
            class="form-input" 
            placeholder="请输入密码" 
            v-model="registerForm.password"
            password
            maxlength="50"
          />
        </view>

        <view class="input-group">
          <input 
            class="form-input" 
            placeholder="请确认密码" 
            v-model="registerForm.confirmPassword"
            password
            maxlength="50"
          />
        </view>

        <view class="input-group">
          <input 
            class="form-input" 
            placeholder="请输入昵称（可选）" 
            v-model="registerForm.nickname"
            maxlength="50"
          />
        </view>

        <view class="input-group">
          <input 
            class="form-input" 
            placeholder="请输入邮箱（可选）" 
            v-model="registerForm.email"
            maxlength="100"
          />
        </view>

        <button 
          class="register-button" 
          :class="{ 'loading': isLoading }"
          @click="handleRegister"
          :disabled="isLoading"
        >
          {{ isLoading ? '注册中...' : '注册' }}
        </button>

        <view class="form-footer">
          <text class="login-link" @click="goToLogin">已有账户？立即登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 内联API配置以避免模块导入问题
const BASE_URL = 'http://localhost:3000/api'

function request(options) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      }
    }

    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

const api = {
  user: {
    register(data) {
      return request({
        url: '/users/register',
        method: 'POST',
        data
      })
    }
  }
}

export default {
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        nickname: '',
        email: ''
      },
      isLoading: false
    }
  },

  methods: {
    // 验证表单
    validateForm() {
      if (!this.registerForm.username.trim()) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return false
      }

      if (this.registerForm.username.length < 3) {
        uni.showToast({
          title: '用户名至少3个字符',
          icon: 'none'
        })
        return false
      }

      if (!this.registerForm.password.trim()) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return false
      }

      if (this.registerForm.password.length < 6) {
        uni.showToast({
          title: '密码至少6个字符',
          icon: 'none'
        })
        return false
      }

      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        })
        return false
      }

      if (this.registerForm.email && !this.isValidEmail(this.registerForm.email)) {
        uni.showToast({
          title: '请输入正确的邮箱格式',
          icon: 'none'
        })
        return false
      }

      return true
    },

    // 验证邮箱格式
    isValidEmail(email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      return emailRegex.test(email)
    },

    // 处理注册
    async handleRegister() {
      if (!this.validateForm()) {
        return
      }

      this.isLoading = true

      try {
        // 准备注册数据，确保所有字段都有值（即使是null）
        const registerData = {
          username: this.registerForm.username,
          password: this.registerForm.password,
          nickname: this.registerForm.nickname || this.registerForm.username,
          email: this.registerForm.email || null,
          phone: null // 明确设置为null
        }
        
        console.log('开始注册，发送数据:', {
          ...registerData,
          password: '******' // 不记录实际密码
        })
        
        const response = await api.user.register(registerData)
        
        console.log('注册响应:', response)
        
        if (response.code === 200) {
          // 保存token和用户信息
          uni.setStorageSync('token', response.data.token)
          uni.setStorageSync('userInfo', response.data.user)
          
          uni.showToast({
            title: '注册成功',
            icon: 'success'
          })

          // 延迟跳转，让用户看到成功提示
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/profile/profile'
            })
          }, 1500)
        } else {
          console.error('注册失败，服务器返回错误:', response)
          uni.showToast({
            title: response.message || '注册失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('注册失败，详细错误:', error)
        
        // 显示更详细的错误信息
        let errorMessage = '注册失败，请检查网络连接'
        if (error && error.message) {
          errorMessage = `注册失败: ${error.message}`
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        })
      } finally {
        this.isLoading = false
      }
    },

    // 跳转到登录页面
    goToLogin() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.register-form {
  width: 100%;
  max-width: 600rpx;
  background-color: white;
  border-radius: 30rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.1);
}

.form-header {
  text-align: center;
  margin-bottom: 60rpx;
}

.form-title {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.form-subtitle {
  display: block;
  font-size: 28rpx;
  color: #666;
}

.form-content {
  margin-bottom: 40rpx;
}

.input-group {
  margin-bottom: 30rpx;
}

.form-input {
  width: 100%;
  height: 100rpx;
  background-color: #f8f8f8;
  border-radius: 50rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
}

.form-input:focus {
  border-color: #ff6b6b;
  background-color: white;
}

.register-button {
  width: 100%;
  height: 100rpx;
  background-color: #ff6b6b;
  color: white;
  border-radius: 50rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  margin-bottom: 40rpx;
  transition: all 0.3s ease;
}

.register-button:active {
  background-color: #ff5252;
}

.register-button.loading {
  background-color: #ccc;
}

.form-footer {
  text-align: center;
}

.login-link {
  font-size: 26rpx;
  color: #ff6b6b;
  text-decoration: underline;
}
</style>
